﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Exhibition.Dao.ViewModel;
using AutoMapper;
namespace Exhibition.Dao
{

    public class CodesDao
    {


        public CodesDao()
        {

            Mapper.CreateMap<E_Codes, CodesModel>();
        }
        public List<E_Codes> GetList(int startIndex, int maxRow, out int recordcount)
        {


            using (ExhibitionEntities edm = new ExhibitionEntities())
            {

                recordcount = edm.E_Codes.Count();

                return edm.E_Codes.OrderByDescending(s => s.Id).Skip(startIndex).Take(maxRow).ToList();

            }

        }


        public CodesModel GetOneById(int id)
        {


            using (ExhibitionEntities edm = new ExhibitionEntities())
            {

                var query = edm.E_Codes.FirstOrDefault(s => s.Id == id);
                return Mapper.Map<E_Codes, CodesModel>(query);
            }

        }

        public List<CodesModel> GetModels (int tp){
            using (ExhibitionEntities edm = new ExhibitionEntities())
            {
                return Mapper.Map<List<E_Codes>, List<CodesModel>>(edm.E_Codes.Where(s => s.EType == tp).ToList()); 
            }
        }
        public CodesModel GetOneByCode(string cod)
        {
            using (ExhibitionEntities edm = new ExhibitionEntities())
            {
                return Mapper.Map<E_Codes, CodesModel>(edm.E_Codes.Where(s => s.ECode == cod).FirstOrDefault());
            }
            
        }


        public int Save(CodesModel obj)
        {


            using (ExhibitionEntities edm = new ExhibitionEntities())
            {

                var query = edm.E_Codes.FirstOrDefault(s => s.Id == obj.Id);

                if (query == null)
                {


                    query = new E_Codes();

                    edm.AddToE_Codes(query);

                }


                query.EName = obj.EName;

                query.ECode = obj.ECode;

                query.EType = obj.EType;

                edm.SaveChanges();

                return query.Id;


            }

        }


        public int DelById(int id)
        {


            using (ExhibitionEntities edm = new ExhibitionEntities())
            {

                var query = edm.E_Codes.FirstOrDefault(s => s.Id == id);

                if (query != null)
                {


                    edm.DeleteObject(query);


                }


                return edm.SaveChanges();


            }

        }


    }

}

